package com.ourmovieguy;

import java.util.Iterator;
import java.util.Map;
// import java.util.logging.Logger;

import com.google.wave.api.*;

public class OurMovieGuyRobot extends AbstractRobotServlet {

	private static final long serialVersionUID = -14172943934713362L;
	private static final String pollGadgetUrl = "http://ourmovieguy.appspot.com/Resources/poll.xml";
	
	// private static final Logger log = Logger.getLogger(OurMovieGuyRobot.class.getName());

	@Override
	public void processEvents(RobotMessageBundle bundle) {

		Wavelet wavelet = bundle.getWavelet();
    	Blip rootBlip = wavelet.getRootBlip();
    	
	    if (bundle.wasSelfAdded()) {
	    	Gadget pollGadget = new Gadget(pollGadgetUrl);
	    	rootBlip.getDocument().appendElement(pollGadget);
	    }
	    
	    for (Event e: bundle.getEvents()) {
	    	if (e.getType() == EventType.BLIP_SUBMITTED && bundle.blipHasChanged(rootBlip));
	    	{
	    		Gadget pollGadget = rootBlip.getDocument().getGadgetView().getGadget(pollGadgetUrl);
	    		if (pollGadget != null)
	    		{
	    			Map<String, String> properties = pollGadget.getProperties();
	    			Iterator<String> iter = properties.keySet().iterator();
	    			while (iter.hasNext())
	    			{
	    				String movieName = iter.next().replace("option:", "");
	    				if (movieName.equals("url"))
	    					continue;
	    				
	    				if (!wavelet.hasDataDocument(movieName))
	    				{ 
	    					wavelet.appendDataDocument(movieName, "exists");
	    					
	    					NYTMovie movie = PM.getObjectById(NYTMovie.class, movieName);
	    					String txt = movieName + ":\n";
	    					
	    					if (movie != null)
	    					{
	    						txt += "Movie page: " + movie.getUrl() + "\n";
	    						txt += "Publication date: " + movie.getPub() + "\n";
	    						txt += "Rating: " + movie.getRating();
	    					}

    						Blip movieBlip = wavelet.appendBlip(movieName);
    						TextView textView = movieBlip.getDocument();
    						textView.append(txt);
	    				} 
	    			}
	    		}
	    	}
	    }
	}
}